package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebsocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebsocketServer websocketServer;
    /**
     * 用户下单
     * @param ordersDTO
     * @return
     */
    @Override
    public OrderSubmitVO add(OrdersDTO ordersDTO) {
        // 1.处理各种业务异常（地址为空，购物车为空等等）
        // 1.1 根据地址id查询地址详情
        AddressBook address = new AddressBook();
        address.setUserId(BaseContext.getCurrentId());
        address.setId(ordersDTO.getAddressBookId());
        AddressBook addressbook = addressMapper.getDetail(address);
        if(addressbook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 1.2 判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 2.插入订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID); // 未支付
        orders.setStatus(Orders.PENDING_PAYMENT); // 待付款
        orders.setNumber(String.valueOf((System.currentTimeMillis())));
        orders.setPhone(addressbook.getPhone());
        orders.setConsignee(addressbook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        System.out.println(orders);
//            try {
        orderMapper.insert(orders);
//            } catch (Exception e) {
//                System.out.println(e);
//            }


        // 3.插入订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for(ShoppingCart cart: list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        // 4.清空当前用户的购物车
        shoppingCartMapper.clear(BaseContext.getCurrentId());
         // 5.返回订单号
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }

    /**
     * 支付订单
     * @param orderId
     */
    @Override
    public void pay(String orderId) {
        Orders order = new Orders();
        order.setNumber(orderId);
        order.setUserId(BaseContext.getCurrentId());
        order.setPayStatus(Orders.PAID); // 已支付
        order.setStatus(2);
        orderMapper.pay(order);
        Map map = new HashMap();
        map.put("type", 1); // 1表示支付成功,2表示支付失败
        map.put("orderNumber", orderId);
        map.put("content", "支付成功");
        String json = JSON.toJSONString(map);
        websocketServer.sendToAllClient(json);
    }

    /**
     * 催单
     * @param orderId
     */
    @Override
    public void reminder(Long orderId) {
        Orders order = orderMapper.getById(orderId);
        if(order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", 2); // 1表示支付成功,2表示支付失败
        map.put("orderNumber", orderId);
        map.put("content", "客户催单了");
        String json = JSON.toJSONString(map);
        websocketServer.sendToAllClient(json);
    }

    /**
     * 分页查询订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getOrderList(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 处理分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        // 查询订单
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.list(ordersPageQueryDTO);
        List<Orders> data = page.getResult();
        List<OrderVO> result = new ArrayList();
        // 查询订单详情
        for(Orders i: data) {
            OrderVO item = new OrderVO();
            BeanUtils.copyProperties(i, item);
            List<OrderDetail> orderDetails = orderDetailMapper.list(i.getId());
            item.setOrderDetailList(orderDetails);
            result.add(item);
        }

        return new PageResult(page.getTotal(), result);
    }

    /**
    * 获取订单详情
     * @param orderId
     * @return
     */

    @Override
    public OrderVO getOrderDetail(Long orderId) {
        Orders order = orderMapper.getById(orderId);
        OrderVO result = new OrderVO();
        BeanUtils.copyProperties(order, result);
        List<OrderDetail> orderDetails = orderDetailMapper.list(orderId);
        result.setOrderDetailList(orderDetails);
        AddressBook address = new AddressBook();
        address.setId(order.getAddressBookId());
//        address.setUserId(BaseContext.getCurrentId());
        AddressBook addressData = addressMapper.getDetail(address);
        result.setAddressDetail(addressData);
//        result.set
        return result;
    }

    /**
     * 分页查询
     * @param ordersPageQueryDTO
     * @return
     */

    @Override
    public PageResult  list(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 处理分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.list(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();
        for(Orders i : page.getResult()) {
            OrderVO item = new OrderVO();
            BeanUtils.copyProperties(i, item);
            AddressBook address = new AddressBook();
            address.setId(i.getAddressBookId());
            AddressBook addressBook = addressMapper.getDetail2(address);
            item.setAddressDetail(addressBook);
            list.add(item);
        }
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 下单
     * @param ordersConfirmDTO
     */
    @Override
    public void updateStatus(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(6);
        orderMapper.update(orders);
    }

    /**
     * 拒绝订单
     * @param ordersConfirmDTO
     */
    @Override
    public void rejectOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(6);
        orderMapper.update(orders);
    }
}
